import {
	API_ROOT
} from '@/config/env.js'

let request_root = API_ROOT;
let upload_url = request_root + '/api/upload';
let project_api_type = '商城'; //项目接口类型   Laravel  商城  
if (project_api_type == '商城') {
	request_root += '/service.php'
	upload_url = request_root;
}

// 请求参数
let handleRequestParams = function(params = {}) {
	if (params && !params.token) {
		params.token = uni.getStorageSync('token') || '';
		params.userId = uni.getStorageSync('userId') || '';
	}
	return params
}

// 接口节流
//需要设置节流的接口 比如表单提交类接口需要限制调用的时间间隔
let apiThrottleList = [
	'bindMoble',
	'updateUser',
];
let apiTimeStackList = []; //接口调用时间记录
// 接口节流


// 商城接口模版
// this.$api({
// 	url: '/service.php',
// 	method: 'post',
// 	data: {
// 		action: 'index_index',
// 	},
// })
//
// Laravel 接口模版
// this.$api({
// 	url: '/setting',
// 	method: 'post',
// 	data: {
//
// 	},
// })


let api = (option, params = {}, method) => {
	let apiName = ''
	if (typeof option == 'string') {
		apiName = option;
	} else if (typeof option == 'object') {
		apiName = option.action;
		params = option.data;
		method = option.method || 'post'
	}

	let request_url = project_api_type == 'Laravel' ? request_root + '/api/' + (option.url || '').replace('/', '') :
		request_root;
	params = handleRequestParams(params);

	return new Promise((resolve, reject) => {
		// if (is_not_auth(apiName)) {
		// 	setTimeout(() => {
		// 		uni.navigateTo({
		// 			url: '/pages/login/login'
		// 		})
		// 	}, 1000)
		// 	return resolve({
		// 		code: 0,
		// 		message: '请先登录'
		// 	});
		// }
		let action = apiName;

		if (apiThrottleList.includes(action)) {
			// debugger
			console.log('接口需要节流')
			let ms = new Date().getTime();
			let first_same_item = apiTimeStackList.find(v => v.action == action);
			let time_divider = 0;
			if (first_same_item) {
				time_divider = ms - first_same_item.ms
				console.log('time_divider = ', time_divider)
			}

			//如果时间间隔少于300毫秒  结束本次接口调用
			if (time_divider && time_divider < 400) {
				console.log('接口调用间隔少于400毫秒 禁止继续调取数据')
				// return ({code: 210})

				return resolve({
					code: 210
				})
				// return reject({code: 210})
			} else {
				apiTimeStackList.unshift({
					action: action,
					ms: ms,
				});

				console.log('apiTimeStackList', apiTimeStackList)
			}
		}


		//请求地址
		uni.request({
			method: 'get' || method || "GET",
			url: request_url,
			data: params,
			// sslVerify: false,
			header: {
				'content-type': 'application/x-www-form-urlencoded'
				// 'content-type': 'multipart/form-data'
			},
			dataType: "json",
			success(res) {
				// console.log('api res', res);
				if (res.statusCode != 200) {
					uni.showToast({
						icon: 'none',
						title: (option.url || apiName) + ' 接口网络错误',
						duration: 3000
					});
					return false;
				}
				if (res.data.code === 401) { //用户未登录
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
				resolve(res.data)
			},
			fail(res) {
				console.log(`request调用失败`, res);
			}
		});
	});
}


//上传

// this.$apiUpload({
// 	url: '/service.php',
// 	method: 'post',
// 	data: {
// 		action: 'index_localUpload', //login
// 		img: file,
// 		if_touxiang: 1
// 	},
// }).then(res => {
// 	this.$logjson('index_localUpload 2', res)
// 	if (res.code == 200) {

// 	}
// });

let apiUpload = (option) => {
	let filePath = option.data.img;
	// let filePath = option.data.file;
	delete option.data.img
	let formData = handleRequestParams(option.data);

	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: upload_url,
			filePath: filePath,
			formData: formData,
			name: 'img',
			// name: 'file',
			success: (res) => {
				if (res.statusCode != 200) {
					uni.showToast({
						title: '上传错误',
						duration: 2000
					});
					return false;
				}
				resolve(JSON.parse(res.data))
			},
			fail: (err) => {
				console.warn('err', err)
			}
		});
	});
}

export default {
	api,
	apiUpload,
};